#include "blockqueue.hpp"
#include "Task.hpp"
#include <pthread.h>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>

class threaddata
{
public:
    blockqueue<Task>* bq;
    std::string name;
};

void *consumer(void *args)
{
    threaddata* td = static_cast<threaddata*>(args);
    while(true)
    {
        Task T;
        td->bq->pop(&T);
        T();
        std::cout << "consumer data: " << T.PrintResult() << ", " << td->name << std::endl;
    }
    return NULL;
}

void *producter(void *args)
{   

    blockqueue<Task> *bq = static_cast<blockqueue<Task>*>(args);
    while(true)
    {
         int data1 = rand() % 10; // [1, 10] // 将来深刻理解生产消费，就要从这里入手，TODO
        usleep(rand()%123);
        int data2 = rand() % 10; // [1, 10] // 将来深刻理解生产消费，就要从这里入手，TODO
        usleep(rand()%123);
        char oper = opers[rand() % (opers.size())];//task.hpp
        Task t(data1, data2, oper);
        std::cout << "productor task: " << t.PrintTask() << std::endl;
        // 2. 进行生产
        // bq->Push(data);
        bq->push(t);
        sleep(1);
    }
    return NULL;
}

int main()
{
    srand((uint64_t)time(NULL)^getpid()^pthread_self());
    blockqueue<Task> *bq = new blockqueue<Task>();
    pthread_t c[3], p[2]; 

    threaddata *td = new threaddata();
    td->bq = bq;
    td->name = "thread-1";
    pthread_create(&c[0], NULL, consumer, td);

    threaddata *td1 = new threaddata();
    td1->bq = bq;
    td1->name = "thread-2";
    pthread_create(&c[1], NULL, consumer, td);

    threaddata *td2 = new threaddata();
    td2->bq = bq;
    td2->name = "thread-3";
    pthread_create(&c[2], NULL, consumer, td);

    pthread_create(&p[0], nullptr, producter, bq);
    pthread_create(&p[1], nullptr, producter, bq);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(c[2], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);



}